package com.ming.handler;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ming.exception.MyException;
import com.ming.model.ErrorInfo;

import ch.qos.logback.core.db.dialect.MySQLDialect;

/**
 * Created by yudm on 2016-10-24.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler
    public ModelAndView defaultErrorHandler(HttpServletRequest request,Exception e) throws Exception{
       ModelAndView mav = new ModelAndView();
        mav.addObject("exception",e);
        mav.addObject("url", request.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest request,MyException exception) throws Exception{
    	ErrorInfo<String> errorInfo = new ErrorInfo<>();
    	errorInfo.setCode(errorInfo.ERROR);
    	errorInfo.setMessage(exception.getMessage());
    	errorInfo.setData("some data");
    	errorInfo.setUrl(request.getRequestURL().toString());
    	return errorInfo;
    }

}
